<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" :model="listQuery">
        <el-form-item label="">
          <el-input
            v-model="listQuery.name"
            placeholder="请输入姓名/昵称/微信ID"
            clearable
            size="small"
            @keyup.enter.native="handleFilter"
          ></el-input>
        </el-form-item>
        <el-form-item label="">
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click.native="handleFilter"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增{{ this.title }}</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="success"
            icon="el-icon-bottom"
            size="mini"
            @click="handleGetUserInfos"
            >获取公众号用户信息</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="handleBatchDelete"
            >批量删除</el-button
          >
        </el-form-item>
      </el-form>

      <el-table
        :data="users"
        border
        v-loading="listLoading"
        fit
        highlight-current-row
        style="width: 100%"
        size="small"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" align="center"></el-table-column>
        <el-table-column
          v-for="column in tableColumns"
          :key="column.key"
          :label="column.title"
          :prop="column.key"
          :align="column.align"
          :width="column.width ? column.width : ''"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column align="center" label="操作" width="200px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="handleEdit(scope)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="handleDelete(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getWxUserList"
      />
    </el-card>
    <!-- 对话框表单 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="getTitle"
      width="60%"
      top="10px"
    >
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="100px"
        label-position="right"
        style="width: 95%; padding: 0 30px"
        status-icon
        size="small"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input
                type="text"
                v-model="form.name"
                placeholder="姓名"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="昵称" prop="nickname">
              <el-input
                type="text"
                v-model="form.nickname"
                placeholder="昵称"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="微信ID" prop="openid">
              <el-input
                type="text"
                v-model="form.openid"
                placeholder="电话号码"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话号码" prop="telephone">
              <el-input
                type="text"
                v-model="form.telephone"
                placeholder="电话号码"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="form.sex" placeholder="性别" clearable>
                <el-option
                  v-for="item in sexes"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="注册时间" prop="subscribe_time">
              <el-input
                v-model="form.subscribe_time"
                placeholder="注册时间"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="省份" prop="province">
              <el-input v-model="form.province" placeholder="省份" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="城市" prop="city">
              <el-input v-model="form.city" placeholder="城市" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="国家" prop="country">
              <el-input v-model="form.country" placeholder="国家" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="使用语言" prop="language">
              <el-input
                v-model="form.language"
                placeholder="使用语言"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="头像" prop="headimgurl">
              <el-input
                v-model="form.headimgurl"
                placeholder="头像"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="渠道来源" prop="subscribe_scene">
              <el-input
                v-model="form.subscribe_scene"
                placeholder="渠道来源"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="扫码场景" prop="qr_scene">
              <el-input
                v-model="form.qr_scene"
                placeholder="扫码场景"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="统一标识" prop="unionid">
              <el-input
                v-model="form.unionid"
                placeholder="统一标识"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="备注" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="分组ID" prop="groupid">
              <el-input v-model="form.groupid" placeholder="分组ID" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标签列表" prop="tagid_list">
              <el-input
                v-model="form.tagid_list"
                placeholder="标签列表"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="会员卡号" prop="card_num">
              <el-input
                v-model="form.card_num"
                placeholder="会员卡号"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户性质" prop="staff">
              <el-select v-model="form.staff" placeholder="用户性质">
                <el-option
                  v-for="item in staffs"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="可用积分" prop="score">
              <el-input v-model="form.score" placeholder="可用积分" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="不可用积分" prop="unused_score">
              <el-input
                v-model="form.unused_score"
                placeholder="不可用积分"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="是否订阅" prop="subscribe">
          <el-switch v-model="form.subscribe"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false" size="mini">取消</el-button>
        <el-button type="primary" @click="handleSave(false)" size="mini"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  getWxUsers,
  addWxUser,
  updateWxUser,
  delWxUser,
  delWxUsers,
  getUserInfos,
} from "@/api/wechat";

import Pagination from "@/components/Pagination";

const defaultForm = {
  id: null,
  name: null,
  nickname: null,
  openid: null,
  telephone: null,
  sex: null,
  province: null,
  city: null,
  country: null,
  language: null,
  headimgurl: null,
  subscribe_time: null,
  subscribe_scene: null,
  qr_scene: null,
  unionid: null,
  remark: null,
  groupid: null,
  tagid_list: null,
  card_num: "",
  staff: null,
  score: 0,
  unused_score: 0,
};

export default {
  name: "WxUser",
  data() {
    return {
      form: Object.assign({}, defaultForm),
      formRules: {
        // name: [
        //   {
        //     type: "string",
        //     required: true,
        //     message: "请输入姓名",
        //     trigger: "blur",
        //   },
        // ],
        nickname: [
          {
            required: true,
            message: "请输入昵称",
            trigger: "blur",
          },
        ],
        openid: [
          {
            type: "string",
            required: true,
            message: "请输入微信ID",
            trigger: "blur",
          },
        ],
        // telephone: [
        //   {
        //     type: "string",
        //     required: true,
        //     message: "请输入联系电话",
        //     trigger: "blur",
        //   },
        // ],
      },
      //列名
      tableColumns: [
        {
          key: "name",
          title: "姓名",
          align: "center",
          width: "120",
        },
        {
          key: "nickname",
          title: "昵称",
          align: "center",
          width: "180",
        },
        {
          key: "openid",
          title: "微信ID",
          align: "center",
        },
        {
          key: "telephone",
          title: "手机号码",
          align: "center",
        },
        {
          key: "sex_name",
          title: "性别",
          align: "center",
          width: "60",
        },
        {
          key: "province",
          title: "省份",
          align: "center",
          width: "100",
        },
        {
          key: "city",
          title: "城市",
          align: "center",
        },
        {
          key: "card_num",
          title: "卡号",
          align: "center",
          width: "100",
        },
        {
          key: "score",
          title: "可用积分",
          align: "center",
          width: "100",
        },
        {
          key: "usused_score",
          title: "不可用积分",
          align: "center",
          width: "100",
        },
        {
          key: "subscribe_time",
          title: "关注时间",
          align: "center",
          width: "140",
        },
      ],
      title: "微信用户",
      dialogVisible: false,
      dlgUploadVisible: false,
      dialogType: "new",
      users: [],
      roles: [],
      selections: [],

      sexes: [
        { id: 0, name: "未知" },
        { id: 1, name: "男" },
        { id: 2, name: "女" },
      ],

      staffs: [
        { id: 0, name: "无" },
        { id: 1, name: "管理员" },
        { id: 2, name: "普通员工" },
      ],

      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 15,
        name: null,
      },
    };
  },
  computed: {
    ...mapGetters(["uid"]),
    getTitle() {
      return this.dialogType == "new"
        ? `新增${this.title}`
        : `编辑${this.title}`;
    },
  },
  components: {
    Pagination,
  },
  created() {
    this.getWxUserList();
  },
  methods: {
    getWxUserList() {
      this.listLoading = true;
      getWxUsers(this.listQuery)
        .then((res) => {
          this.users = res.results;
          this.listLoading = false;
          this.total = res.count;
        })
        .catch((error) => {
          console.log(error);
          this.$message.error("获取客户列表失败!");
          this.listLoading = false;
        });
    },

    handleSelectionChange(val) {
      this.selections = val.map((item) => item.id);
      console.log(this.selections);
    },
    handleBatchDelete() {
      if (this.selections.length === 0) {
        this.$message.warning("请选择要删除的记录");
        return;
      }
      this.$confirm("确定要删除选中记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const sel_ids = {
            select_ids: this.selections,
          };
          const res = await delWxUsers(sel_ids);
          this.getWxUserList();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },
    handleGetUserInfos() {
      this.listLoading = true;
      getUserInfos()
        .then((res) => {
          console.log(res);
          if (res) {
            this.getWxUserList();
          }
          this.listLoading = false;
        })
        .catch((error) => {
          this.listLoading = false;
          this.$message.error("拉取用户信息失败");
        });
    },
    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getWxUserList();
    },
    // 增加
    handleAdd() {
      this.form = Object.assign({}, defaultForm);

      this.dialogType = "new";
      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 修改
    handleEdit(scope) {
      this.form = Object.assign({}, scope.row);
      this.dialogType = "edit";

      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 删除
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除这条记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delWxUser(row.id);
          this.users.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },
    // 保存操作
    async handleSave(flag) {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";
        let res = null;
        if (isEdit) {
          res = await updateWxUser(this.form);
          const index = this.users.findIndex((v) => v.id === res.id);
          this.users.splice(index, 1, res);
        } else {
          res = await addWxUser(this.form);
          const { id } = res;
          if (id > 0) {
            this.users.unshift(res);
          }
        }

        const { name, nickname, telephone } = res;
        if (flag) {
          this.form = Object.assign({}, defaultForm);
          this.dialogType = "new";
        } else {
          this.dialogVisible = false;
        }

        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>姓名: ${name}</div>
              <div>昵称: ${nickname}</div>
              <div>电话: ${telephone}</div>
            `,
          type: "success",
        });
      });
    },
  },
};
</script>

<style lang='scss' scoped>
.dialog .el-form {
  margin-top: 20px;
}
.el-form-item {
  margin-bottom: 15px;
}
</style>